package com.sita.cfmoto.interact.activity;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyTrafficStyle;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMChatRoomChangeListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.sita.cfmoto.R;
import com.sita.cfmoto.beans.PersonBean;
import com.sita.cfmoto.rest.RestClient;
import com.sita.cfmoto.rest.model.Active;
import com.sita.cfmoto.rest.model.FetchUserRestResponse;
import com.sita.cfmoto.support.Constants;
import com.sita.cfmoto.support.GlobalContext;
import com.sita.cfmoto.support.LocationController;
import com.sita.cfmoto.ui.view.MarqueeTextView;
import com.sita.cfmoto.utils.AccountUtils;
import com.sita.cfmoto.utils.BitmapUtils;
import com.sita.cfmoto.utils.LocalStorage;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class ActiveShareActivity extends AppCompatActivity implements AMap.OnMarkerClickListener,
        AMap.OnInfoWindowClickListener,
        AMap.OnMarkerDragListener,
        AMap.OnMapLoadedListener,
        AMap.InfoWindowAdapter {

    private final String TAG = ActiveShareActivity.class.getSimpleName();
    private final int AVATAR_ICON_BG_WIDTH = 50;
    private final int AVATAR_ICON_HEAD_WIDTH = 40;
    private final int POI_ICON_WIDTH = 30;
    private final float MARKER_ANCHOR_POSITION_H = 0.5f;
    private final float MARKER_ANCHOR_POSITION_V = 1f;
    private final float MARKER_ALPHA = 1f;
    private final boolean FLAG_SHARE_JOIN = true;
    private final boolean FLAG_SHARE_EXIT = false;
    private final String ACTION_SHARE_LOCATION = "aliveLocShare";
    private final String ACTION_SHARE_SENDER = "senderId";
    private final String ACTION_SHARE_LAT = "lat";
    private final String ACTION_SHARE_LNG = "lng";
    private final String ACTION_SHARE_NOTE = "note";
    @Bind(R.id.share_location_map)
    TextureMapView mapView;
    @Bind(R.id.share_notification_text)
    MarqueeTextView mNotificationText;
    private EMMessageListener msgListener;
    private EMChatRoomChangeListener chatRoomChangeListener;
    private AMap aMap;
    private Active mActive;
    private String chatRoomId;
    AMapLocationListener shareLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                sendShareLocMessage(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()));
            }
        }
    };
    private Marker myMarker, startMarker, destinationMarker;
    private MarkerOptions myMarkerOption;
    private Map<String, Marker> mapUsersMarker = new HashMap<>();
    private LinkedList<ChatRoomMessage> mChatRoomMessageList = new LinkedList<>();
    private UserTarget myUserTarget;
    private Map<String, UserTarget> usersTargetMap = new HashMap<>();
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            return false;
        }
    });

    @OnClick(R.id.share_exit_btn)
    void onExit() {
        this.finish();
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
        Log.d(TAG, "onInfoWindowClick: ");
    }

    @Override
    public void onMapLoaded() {
        moveBounds();
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        if (marker.isInfoWindowShown()) {
            marker.hideInfoWindow();
        } else {
            marker.showInfoWindow();
        }
        return true;
    }

    @Override
    public void onMarkerDragStart(Marker marker) {

    }

    @Override
    public void onMarkerDrag(Marker marker) {

    }

    @Override
    public void onMarkerDragEnd(Marker marker) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_active_share);
        ButterKnife.bind(this);

        mActive = (Active) getIntent().getSerializableExtra("active");
        chatRoomId = mActive.chatroomId;
        initMap(savedInstanceState);
        joinChatRoom(chatRoomId);
        msgListener = new EMMessageListener() {

            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                //收到消息

            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> messages) {
                //收到透传消息
                for (EMMessage message : messages) {
                    Log.d(TAG, "receive command message");
                    //get message body
                    EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
                    final String action = cmdMsgBody.action();//获取自定义action
                    if (message.getChatType() == EMMessage.ChatType.ChatRoom &&
                            message.getTo().equals(chatRoomId) &&
                            !TextUtils.isEmpty(action) &&
                            action.equals(ACTION_SHARE_LOCATION)) {

                        String from = message.getFrom();
                        String sendId = message.getStringAttribute(ACTION_SHARE_SENDER, "");
                        String lat = message.getStringAttribute(ACTION_SHARE_LAT, "0");
                        String lng = message.getStringAttribute(ACTION_SHARE_LNG, "0");

                        if (from.equals(AccountUtils.getInstance().getAccountID())) {
                            Log.d(TAG, String.format("receive message from myself"));
                            continue;
                        }

                        RestClient.getRestNormalService().fetchUserInfo(from, new Callback<FetchUserRestResponse>() {
                            @Override
                            public void success(FetchUserRestResponse restResponse, Response response) {
                                if (restResponse.mErrorCode.equals("0") && restResponse.mUsers != null) {
                                    String json = RestClient.getGson().toJson(restResponse.mUsers);

                                    if (restResponse.mUsers.get(0) != null) {
                                        AccountUtils.getInstance().addUser(restResponse.mUsers.get(0));
                                        drawMarkersToMap(new LatLng(Double.valueOf(lat), Double.valueOf(lng)), from);
                                    }
                                    Log.d(TAG, "success: " + from + ":");
                                }
                            }

                            @Override
                            public void failure(RetrofitError error) {

                            }
                        });


                        Log.d(TAG, String.format("Command：action:%s,message:%s", action, message.toString()));
                        Log.d(TAG, String.format("from:%s,sendid:%s, lat:%s, lng:%s,", from, sendId, lat, lng));
                    }
                }

            }

            @Override
            public void onMessageReadAckReceived(List<EMMessage> messages) {
                //收到已读回执
            }

            @Override
            public void onMessageDeliveryAckReceived(List<EMMessage> message) {
                //收到已送达回执
            }

            @Override
            public void onMessageChanged(EMMessage message, Object change) {
                //消息状态变动
            }
        };

        chatRoomChangeListener = new EMChatRoomChangeListener() {
            @Override
            public void onChatRoomDestroyed(String s, String s1) {

            }

            @Override
            public void onMemberJoined(String s, String s1) {
                Log.d(TAG, String.format("new comer %s come into chat room: %s", s1, s));
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        PersonBean personBean = new PersonBean();
                        personBean = AccountUtils.getInstance().getUser(s1);
                        if (personBean == null) {
                            RestClient.getRestNormalService().fetchUserInfo(s1, new Callback<FetchUserRestResponse>() {
                                @Override
                                public void success(FetchUserRestResponse restResponse, Response response) {
                                    if (restResponse.mErrorCode.equals("0") && restResponse.mUsers != null) {
                                        if (restResponse.mUsers.get(0) != null) {
                                            AccountUtils.getInstance().addUser(restResponse.mUsers.get(0));
                                            showMemberNotification(s1, FLAG_SHARE_JOIN);
                                        }
                                    }
                                }

                                @Override
                                public void failure(RetrofitError error) {

                                }
                            });
                        } else {
                            showMemberNotification(s1, FLAG_SHARE_JOIN);
                        }
                    }
                });
            }

            @Override
            public void onMemberExited(String s, String s1, String s2) {
                Log.d(TAG, String.format(" %s leave chat room: %s", s2, s + s1));

                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        /*remove marker*/
                        Marker userMarker = mapUsersMarker.get(s2);
                        if (userMarker != null) {
                            userMarker.remove();
                        }
                        /*notification*/
                        showMemberNotification(s2, FLAG_SHARE_EXIT);
                    }
                });

            }

            @Override
            public void onMemberKicked(String s, String s1, String s2) {

            }
        };

        initNotificationLayout();
    }

    private void initNotificationLayout() {
        mNotificationText.setText("");
    }

    private void showMemberNotification(String accountId, boolean join) {
        Log.d(TAG, "showMemberNotification");
        String user = AccountUtils.getInstance().getUserNickName(accountId);
        String message = String.format(getResources().getString(join == FLAG_SHARE_JOIN ? R.string.share_notification_text_join : R.string.share_notification_text_exit), user);
        ChatRoomMessage chatRoomMessage = new ChatRoomMessage(message, accountId, System.currentTimeMillis());
        /*add message list*/
        message = "";

        mChatRoomMessageList.addFirst(chatRoomMessage);
        for (int i = mChatRoomMessageList.size() - 1; i >= 0; i--) {
            ChatRoomMessage msg = mChatRoomMessageList.get(i);
            if (msg.from.equals(chatRoomMessage.from) && msg.timeStamp != chatRoomMessage.timeStamp) {
                mChatRoomMessageList.remove(msg);
                continue;
            }
            message += msg.message + "      ";
        }
        message += "                                       ";

        if (mChatRoomMessageList.size() > 0) {
            mNotificationText.setVisibility(View.VISIBLE);
            message = String.format(getResources().getString(R.string.share_notification_text), message);
            mNotificationText.setText(message);
        }
    }

    protected void initMap(Bundle savedInstanceState) {
        mapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mapView.getMap();
            setMapUi();
            setMapListener();
            setTraffic();
        }

        AMapLocation location = LocationController.getLastKnownLocation();
        LatLng latLng = (location == null) ? null : new LatLng(location.getLatitude(), location.getLongitude());

        setMapCamera(latLng);
        drawMyMarkersToMap(latLng);
        drawStartMarker(new LatLng(Float.valueOf(mActive.deptLat), Float.valueOf(mActive.deptLng)));
        drawDestinationMarker(new LatLng(Float.valueOf(mActive.arriLat), Float.valueOf(mActive.arriLng)));

    }

    private void setMapCamera(LatLng latLng) {
        latLng = (latLng == null) ? Constants.DEFAULT_MAP_CENTER_LATLNG : latLng;
        CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(0).build();
        CameraUpdate update = CameraUpdateFactory.newCameraPosition(cameraPosition);
        aMap.moveCamera(update);
    }

    private void setMapUi() {
        UiSettings mUiSettings = aMap.getUiSettings();
        mUiSettings.setZoomControlsEnabled(true);
        mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);
    }

    private void setMapListener() {
        aMap.setOnMarkerDragListener(this);// 设置marker可拖拽事件监听器
        aMap.setOnMapLoadedListener(this);// 设置amap加载成功事件监听器
        aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
        aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
        aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
//        aMap.setOnMapLongClickListener(this);
//        aMap.setOnMapClickListener(this);
    }

    private void setTraffic() {
        MyTrafficStyle myTrafficStyle = new MyTrafficStyle();
        myTrafficStyle.setSeriousCongestedColor(0xff92000a);
        myTrafficStyle.setCongestedColor(0xffea0312);
        myTrafficStyle.setSlowColor(0xffff7508);
        myTrafficStyle.setSmoothColor(0xff00a209);
        aMap.setTrafficEnabled(false);
    }

    public void moveBounds() {
        LatLngBounds bounds = new LatLngBounds.Builder().include(startMarker.getPosition()).include(destinationMarker.getPosition()).build();
        aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 150));
    }

    /**
     * 在地图上添加marker
     */
    private void drawStartMarker(final LatLng latLng) {
        if (startMarker == null) {
            MarkerOptions markerOptions = new MarkerOptions();
            int widthPix = BitmapUtils.dp2px(GlobalContext.getGlobalContext(), POI_ICON_WIDTH);
            Bitmap tmpBitmap = BitmapUtils.decodeSampledBitmapFromResource(getResources(), R.mipmap.flag_start, widthPix, widthPix);
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(tmpBitmap);
            markerOptions.position(latLng);
            markerOptions.title("起点").snippet(mActive.deptAddr);
            markerOptions.draggable(true);
            markerOptions.icon(icon);
            // 将Marker设置为贴地显示，可以双指下拉看效果
            markerOptions.setFlat(false);
            startMarker = aMap.addMarker(markerOptions);
        } else {
            Log.d(TAG, "old marker");
            startMarker.setPosition(latLng);
        }
    }

    private void drawDestinationMarker(final LatLng latLng) {
        if (destinationMarker == null) {
            MarkerOptions markerOptions = new MarkerOptions();
            int widthPix = BitmapUtils.dp2px(GlobalContext.getGlobalContext(), POI_ICON_WIDTH);
            Bitmap tmpBitmap = BitmapUtils.decodeSampledBitmapFromResource(getResources(), R.mipmap.flag_destination, widthPix, widthPix);
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(tmpBitmap);
            markerOptions.position(latLng);
            markerOptions.title("终点").snippet(mActive.arriAddr);
            markerOptions.draggable(true);
            markerOptions.icon(icon);
            // 将Marker设置为贴地显示，可以双指下拉看效果
            markerOptions.setFlat(false);
            destinationMarker = aMap.addMarker(markerOptions);
        } else {
            Log.d(TAG, "old marker");
            destinationMarker.setPosition(latLng);
        }
    }

    private void drawMyMarkersToMap(final LatLng latlng) {
        if (myMarker == null) {
            myUserTarget = new UserTarget(AccountUtils.getInstance().getAccountID(), latlng);
            Picasso.with(this).load(AccountUtils.getInstance().getAvatar()).into(myUserTarget);

        } else {
            Log.d(TAG, "d");
            myMarker.setPosition(latlng);
        }
    }

    private void addMyMarker(Bitmap avatar, LatLng latLng) {
        if (myMarkerOption == null) {
            myMarkerOption = new MarkerOptions();
        }
        Bitmap tmpBitmap = avatar.copy(avatar.getConfig(), false);
        int widthPix = BitmapUtils.dp2px(GlobalContext.getGlobalContext(), AVATAR_ICON_BG_WIDTH);
        int headPix = BitmapUtils.dp2px(GlobalContext.getGlobalContext(), AVATAR_ICON_HEAD_WIDTH);
        tmpBitmap = BitmapUtils.scaleBitmap(tmpBitmap, widthPix, widthPix);
        tmpBitmap = BitmapUtils.composeBitmap(R.mipmap.avatar_bg, tmpBitmap, widthPix, headPix, MARKER_ALPHA);
        BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(tmpBitmap);

        myMarkerOption.anchor(MARKER_ANCHOR_POSITION_H, MARKER_ANCHOR_POSITION_V);
        myMarkerOption.position(latLng);
        myMarkerOption.title("自己");
        myMarkerOption.draggable(true);
        myMarkerOption.icon(icon);
        // 将Marker设置为贴地显示，可以双指下拉看效果
        myMarkerOption.setFlat(false);
        myMarker = aMap.addMarker(myMarkerOption);

    }


    /**
     * 在地图上添加marker
     */
    private void drawMarkersToMap(final LatLng latlng, String accountId) {
        if (accountId.equals(AccountUtils.getInstance().getAccountID())) {
            drawMyMarkersToMap(latlng);
            return;
        }

        Marker userMarker = mapUsersMarker.get(accountId);

        if (userMarker == null) {

            UserTarget userTarget = usersTargetMap.get(accountId);
            if (userTarget == null) {
                userTarget = new UserTarget(accountId, latlng);
                usersTargetMap.put(accountId, userTarget);
            }
            String avatar = AccountUtils.getInstance().getUser(accountId).user.getAvatar();
            Picasso.with(this).load(avatar).into(userTarget);

        } else {
            userMarker.setPosition(latlng);
        }
    }

    private void addMarkerToMap(LatLng latLng, String accoundId, Bitmap avatar) {
        if (accoundId.equals(AccountUtils.getInstance().getAccountID())) {
            addMyMarker(avatar, latLng);
        } else {
            addFriendMarkerToMap(latLng, accoundId, avatar);
        }
    }

    private void addFriendMarkerToMap(LatLng latlng, String accountId, Bitmap friendAvatar) {
        //判断ID对应的marker有没有
        if (!mapUsersMarker.containsKey(accountId)) {
            //如果不存在
            MarkerOptions friendMarkerOption = new MarkerOptions();
            friendMarkerOption.position(latlng);
            friendMarkerOption.title(AccountUtils.getInstance().getUserNickName(accountId));
            friendMarkerOption.draggable(true);
            Bitmap tmpBitmap = friendAvatar.copy(friendAvatar.getConfig(), false);
            int widthPix = BitmapUtils.dp2px(GlobalContext.getGlobalContext(), AVATAR_ICON_BG_WIDTH);
            int headPix = BitmapUtils.dp2px(GlobalContext.getGlobalContext(), AVATAR_ICON_HEAD_WIDTH);
            tmpBitmap = BitmapUtils.scaleBitmap(tmpBitmap, widthPix, widthPix);
            tmpBitmap = BitmapUtils.composeBitmap(R.mipmap.avatar_bg, tmpBitmap, widthPix, headPix, MARKER_ALPHA);
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(tmpBitmap);
            friendMarkerOption.icon(icon);
            // 将Marker设置为贴地显示，可以双指下拉看效果
            friendMarkerOption.setFlat(false);
            Marker friendMarker = aMap.addMarker(friendMarkerOption);
            mapUsersMarker.put(accountId, friendMarker);
        } else {
            Marker friendMarker = mapUsersMarker.get(accountId);
            friendMarker.setPosition(latlng);
        }
    }


    private void joinChatRoom(String roomId) {
        //roomId为聊天室ID
        EMClient.getInstance().chatroomManager().joinChatRoom(roomId, new EMValueCallBack<EMChatRoom>() {

            @Override
            public void onSuccess(EMChatRoom value) {
                Log.e(TAG, "join success");
                //加入聊天室成功,开始共享位置
                startShareLocation();
            }

            @Override
            public void onError(final int error, String errorMsg) {
                Log.e(TAG, "join fail" + errorMsg);
                //加入聊天室失败
            }
        });
    }

    private void leaveChatRoom(String chatRoomId) {
        Log.d(TAG, "leave ChatRoom ");
        EMClient.getInstance().chatroomManager().leaveChatRoom(chatRoomId);
    }

    private void startShareLocation() {
        Log.d(TAG, "start share location");
        LocationController.startTracking(shareLocationListener, 10000);
    }

    private void stopShareLocation() {
        Log.d(TAG, "stop share location");
        LocationController.stopTracking(shareLocationListener);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(chatRoomChangeListener);
        if (mapView != null) {
            mapView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);
        EMClient.getInstance().chatroomManager().removeChatRoomChangeListener(chatRoomChangeListener);
        if (mapView != null) {
            mapView.onPause();
        }
    }

    @OnClick({R.id.back_img, R.id.active_detail})
    void leaveShare() {
        this.onBackPressed();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mapView != null) {
            mapView.onSaveInstanceState(outState);
        }
    }

    @Override
    public void onDestroy() {
        if (mapView != null) {
            mapView.onDestroy();
        }
        leaveChatRoom(chatRoomId);
        stopShareLocation();
        super.onDestroy();
    }

    private void sendShareLocMessage(LatLng latlng) {
        //发送透传消息
        EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD);
        //支持单聊和群聊，默认单聊，如果是群聊添加下面这行
        cmdMsg.setChatType(EMMessage.ChatType.ChatRoom);
        String action = ACTION_SHARE_LOCATION;//action可以自定义
        EMCmdMessageBody cmdBody = new EMCmdMessageBody(action);
        cmdMsg.setReceipt(chatRoomId);//发送给某个人,聊天室id
        cmdMsg.setAttribute(ACTION_SHARE_LAT, String.valueOf(latlng.latitude));
        cmdMsg.setAttribute(ACTION_SHARE_LNG, String.valueOf(latlng.longitude));
        cmdMsg.setAttribute(ACTION_SHARE_NOTE, "no use");
        cmdMsg.setAttribute(ACTION_SHARE_SENDER, String.valueOf(LocalStorage.getAccountId()));
        cmdMsg.addBody(cmdBody);
        EMClient.getInstance().chatManager().sendMessage(cmdMsg);
        cmdMsg.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                Log.d(TAG, "send share location success");
            }

            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onProgress(int i, String s) {
            }
        });
    }

    class ChatRoomMessage {
        public String message;
        public String from;
        public long timeStamp;
        public ChatRoomMessage(String message, String from, long time) {
            this.message = message;
            this.from = from;
            this.timeStamp = time;
        }
    }

    class UserTarget implements Target {
        public LatLng latLng;
        public String accoundId;

        public UserTarget(String accountId, LatLng latLng) {
            this.latLng = latLng;
            this.accoundId = accountId;
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {

        }

        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Bitmap tmpBitmap = bitmap.copy(bitmap.getConfig(), false);
                    addMarkerToMap(latLng, accoundId, tmpBitmap);
                }
            });

        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {

        }
    }
}